<template>
    <!-- 面包屑 -->
    <!-- <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb> -->
    <!-- 主体区域 -->
    <el-card class="mt16">
        <!-- 搜索和添加用户区 -->
        <el-row :gutter="20">
            <el-col :span="6">
                <el-input @input="fangdou" clearable @clear="getUserList" v-model="userDataObj.query"
                    placeholder="请输入要搜索的内容" class="input-with-select">
                    <template #append>
                        <el-button @click="getUserList" :icon="Search" />
                    </template>
                </el-input>
            </el-col>
            <el-col :span="18">
                <el-button type="primary" @click="openAddUserDia">添加用户</el-button>
            </el-col>
        </el-row>
        <!-- 用户列表 -->
        <el-table border class="mt16" :data="userListArr">
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="姓名" prop="username"></el-table-column>
            <el-table-column label="邮箱" prop="email"></el-table-column>
            <el-table-column label="电话" prop="mobile"></el-table-column>
            <el-table-column label="角色" prop="role_name"></el-table-column>
            <el-table-column label="状态">
                <template #default="scope">
                    <div>
                        <el-switch @change="changeUserStatus(scope.row)" v-model="scope.row.mg_state"></el-switch>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <div>
                        <!-- 编辑用户 -->
                        <el-button type="primary" @click="openEditUserDia(scope.row)" :icon="Edit" size="small"></el-button>
                        <!-- 删除用户 -->
                        <el-button type="warning" :icon="Delete" size="small"></el-button>
                        <!-- 分配用户状态 -->
                        <el-button type="danger" :icon="Setting" size="small"
                            @click="openSetRoleDia(scope.row)"></el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination class="mt16" v-model:current-page="userDataObj.pagenum" v-model:page-size="userDataObj.pagesize"
            :page-sizes="[3, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog v-model="isAddUser" title="添加用户" width="50%" :before-close="handleClose">
        <el-form ref="addUserRef" :rules="addUserRules" label-width="100px" :model="addUserObj">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="addUserObj.username" placeholder="请输入用户名"></el-input>
            </el-form-item>

            <el-form-item label="密码" prop="password">
                <el-input v-model="addUserObj.password" placeholder="请输入密码"></el-input>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
                <el-input v-model="addUserObj.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>

            <el-form-item label="电话" prop="mobile">
                <el-input v-model="addUserObj.mobile" placeholder="请输入电话"></el-input>
            </el-form-item>



        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="isAddUser = false">取消</el-button>
                <el-button type="primary" @click="addUserOk">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>


    <!-- 编辑用户对话框 -->
    <el-dialog v-model="isEditUser" title="编辑用户" width="50%" :before-close="handleClose">
        <el-form ref="addUserRef" :rules="addUserRules" label-width="100px" :model="addUserObj">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="addUserObj.username" placeholder="请输入用户名"></el-input>
            </el-form-item>


            <el-form-item label="邮箱" prop="email">
                <el-input v-model="addUserObj.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>

            <el-form-item label="电话" prop="mobile">
                <el-input v-model="addUserObj.mobile" placeholder="请输入电话"></el-input>
            </el-form-item>



        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="isEditUser = false">取消</el-button>
                <el-button type="primary" @click="EditUserOk">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog v-model="isSetRole" title="分配角色" width="30%" :before-close="handleClose">

        <el-row>
            <el-col :span="5">当前用户：</el-col>
            <el-col :span="19">{{ currentUserObj.username }}</el-col>
        </el-row>

        <el-row class="mt16">
            <el-col :span="5">当前角色：</el-col>
            <el-col :span="19">{{ currentUserObj.role_name }}</el-col>
        </el-row>

        <el-row class="mt16">
            <el-col :span="5">分配角色：{{ currentUserObj.role_id }}</el-col>
            <el-col :span="19">
                <el-select v-model="currentUserObj.role_id" class="m-2" placeholder="请选择新角色" size="large">
                    <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id" />
                </el-select>
            </el-col>
        </el-row>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="isSetRole = false">取消</el-button>
                <el-button type="primary" @click="setRoleOk">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ArrowRight, Search, Edit, Delete, Setting } from '@element-plus/icons-vue'
import { onMounted, reactive, ref } from 'vue'
import * as API from '@/http/api'
import _ from 'lodash'
import type { FormRules, FormInstance } from 'element-plus'
import type { IRoleItem } from '@/dataType/index'

onMounted(() => {
    getUserList()
})

const isSetRole = ref(false)

//当前用户信息
const currentUserObj = reactive({
    //角色id
    role_id: '',
    //角色名称
    role_name: '',
    //当前用户名
    username: ''

})

//点击确定分配角色
const setRoleOk = () => {
    console.log('当前用户id:', userId.value)
    console.log('当前角色id:', currentUserObj.role_id)

    //调用分配角色接口
}


const roleList = ref<IRoleItem[]>([])

//打开用户分配角色对话框
const openSetRoleDia = async (row: { id: number, username: string, role_name: string }) => {
    console.log('当前用户信息：', row)
    userId.value = row.id;
    currentUserObj.role_name = row.role_name;
    currentUserObj.username = row.username;

    //调用角色列表接口
    const res = await API.getRoleListApi()
    roleList.value = res.data
    console.log('角色列表：', res)

    isSetRole.value = true
}

//点击确定编辑将编辑的数据更新到后台
const EditUserOk = () => {
    //验证表单
    addUserRef.value?.validate(async valid => {
        if (!valid) return
        //如果合法调用编辑接口
        await API.editUserApi(userId.value, {
            email: addUserObj.email,
            mobile: addUserObj.mobile
        })

        //隐藏对话框
        isEditUser.value = false
        //更新列表
        getUserList()

    })

}

//是否显示编辑
const isEditUser = ref(false)
//当前用户id
const userId = ref(-1)

//打开添加用户对话框
const openEditUserDia = (row: { id: number, username: string; mobile: string; email: string }) => {
    console.log(row)
    //拿到用户id
    userId.value = row.id

    //回填数据
    addUserObj.username = row.username
    addUserObj.email = row.email
    addUserObj.mobile = row.mobile

    isEditUser.value = true
}

//改变用户状态
type UserStatusType = { id: number, mg_state: boolean }
const changeUserStatus = async (row: UserStatusType) => {
    //调改变状态接口
    await API.changeUserStatusApi(row.id, row.mg_state)
}

const checkEmailFn = (rule: any, value: any, callback: any) => {
    //验证邮箱正则表达式
    const emailPattern = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
    //检测是否合法
    if (!emailPattern.test(value)) {
        return callback(new Error('您的邮箱格式输入不合法，请检查，应该这样：hjl@126.com'))
    }

    callback()
}

//验证手机号
const checkMobileFn = (rule: any, value: any, callback: any) => {
    //验证手机号正则
    const reg = /^1[3456789]\d{9}$/
    if (!reg.test(value)) {
        return callback(new Error('您的手机号格式输入不合法，请检查，应该这样：13xxxxxxxxx'))

    }

    callback()

}



//添加用户表单验证规则
const addUserRules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入新用户名', trigger: 'blur' },
        { min: 5, max: 20, message: '新用户名长度5~20长度之间', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 20, message: '新密码长度5~20长度之间', trigger: 'blur' },
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { validator: checkEmailFn, trigger: 'blur' }
    ],
    mobile: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { validator: checkMobileFn, trigger: 'blur' }

    ],
})



//添加用户对象
const addUserObj = reactive({
    username: '',
    password: '',
    email: '',
    mobile: ''
})


//是否显示隐藏添加用户
const isAddUser = ref(false)

//关闭添加用户对话框前是否触发做一些清理操作
const handleClose = () => {
    addUserObj.username = ''
    addUserObj.password = ''
    addUserObj.email = ''
    addUserObj.mobile = ''
    isAddUser.value = false
}

const addUserRef = ref<FormInstance>()
//点击确定将新用户信息添加到后台
const addUserOk = () => {
    addUserRef.value?.validate(async valid => {
        console.log(valid)
        //不合法直接返回
        if (!valid) return
        //调用添加用户接口
        await API.addUserListApi(addUserObj)

        addUserObj.username = ''
        addUserObj.password = ''
        addUserObj.email = ''
        addUserObj.mobile = ''
        //隐藏对话框
        isAddUser.value = false
        //展示用户列表
        getUserList()
    })
}

//打开添加用户对话框
const openAddUserDia = () => {
    addUserObj.mobile = ''
    addUserObj.username = ''
    addUserObj.password = ''
    addUserObj.email = ''
    // addUserRef.value?.resetFields()
    //显示对话框
    isAddUser.value = true;
}

//利用lodash实现防抖
const fangdou = _.debounce(() => {
    getUserList()
}, 300)

//利用lodash实现节流
const jieliu = _.throttle(() => {
    getUserList()
}, 3000)



const userDataObj = reactive({
    query: '',
    pagesize: 5,
    pagenum: 1
})

//定义用户列表数组
const userListArr = ref([])

//总用户数
const total = ref(0)

//获取用户列表
const getUserList = async () => {
    //调用户列表接口
    const res = await API.getUserListApi(userDataObj)
    console.log('用户列表111：', res)
    userListArr.value = res.data.users;
    total.value = res.data.total;

}

//每页条数改变时触发函数
const handleSizeChange = (val: number) => {
    console.log('每页条数改变时触发函数:', val)
    userDataObj.pagesize = val;
    getUserList()
}

//当前页码改变时触发的函数
const handleCurrentChange = (val: number) => {
    console.log('当前页码改变时触发的函数:', val)
    userDataObj.pagenum = val
    getUserList()

}

</script>

<style scoped>
@import "@/assets/public.css";
</style>